package types

import (
	"github.com/iancoleman/strcase"
	"github.com/vektah/gqlparser/v2/ast"
	"gqlgen-generator/config"
	"gqlgen-generator/gen/graphql/context"
	"gqlgen-generator/gen/graphql/scalars"
	"gqlgen-generator/gen/table"
	"strings"
)

func BuildTableModel(ctx *context.GqlBuildContext) (def *ast.Definition) {
	def = &ast.Definition{}
	def.Kind = ast.Object
	def.Description = ctx.TableDesc
	def.Name = TableModelName(ctx.TableName)
	// build fields
	fieldList := make([]*ast.FieldDefinition, 0)
	for _, columnInfo := range ctx.Columns {
		fieldList = append(fieldList, GetColumnFieldDefinition(ctx, columnInfo))
	}
	def.Fields = fieldList
	return
}

func TableModelName(tableName string) string {
	return strcase.ToCamel(tableName)
}

// 获取列的类型
func GetColumnFieldDefinition(ctx *context.GqlBuildContext, columnInfo table.ColumnInfo) *ast.FieldDefinition {
	relation := FindRelation(ctx, columnInfo)
	if relation == nil {
		return &ast.FieldDefinition{
			Description:  columnInfo.Columndesc,
			Name:         columnInfo.Columnname,
			Arguments:    nil,
			DefaultValue: nil,
			Type: &ast.Type{
				NamedType: scalars.CalculateNamedType(columnInfo),
				NonNull:   !columnInfo.Nullable,
				Position:  nil,
			},
			Directives: nil,
			Position:   nil,
		}
	}
	return &ast.FieldDefinition{
		Description:  columnInfo.Columndesc,
		Name:         strings.ReplaceAll(columnInfo.Columnname, "_id", ""),
		Arguments:    nil,
		DefaultValue: nil,
		Type: &ast.Type{
			NamedType: TableModelName(relation.ToTable),
			NonNull:   false,
			Position:  nil,
		},
		Directives: nil,
		Position:   nil,
	}

}

// 获取列的relation
func FindRelation(ctx *context.GqlBuildContext, columnInfo table.ColumnInfo) *config.TableRelationConf {
	if len(ctx.Relations) == 0 {
		return nil
	}
	for _, relation := range ctx.Relations {
		if relation.Table != ctx.TableName {
			continue
		}
		if relation.Column == columnInfo.Columnname {
			return &relation
		}
	}
	return nil
}
